package com.demo.homework;


import java.io.*;

public class School implements Serializable {
    private String name;
    private String address;
    private int birthYear;

    public School(String name, String address, int birthYear) {
        this.name = name;
        this.address = address;
        this.birthYear = birthYear;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getBirthYear() {
        return birthYear;
    }

    public void setBirthYear(int birthYear) {
        this.birthYear = birthYear;
    }

    @Override
    public String toString() {
        return "School{" +
                "name='" + name + '\'' +
                ", address='" + address + '\'' +
                ", birthYear=" + birthYear +
                '}';
    }
    public static void writeToFile() throws IOException {
        //创建一个对象流写入二进制文件
        ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("day05//1.dat"));
        //创建2个对象
        School school = new School("张三", "晋江", 2020);
        School school1 = new School("李四", "泉州", 2022);
        oos.writeObject(school);
        oos.writeObject(school1);
        oos.close();
        System.out.println("写入成功");

    }
    public static void readFromFile() throws IOException, ClassNotFoundException {
        ObjectInputStream ois=new ObjectInputStream(new FileInputStream("day05//1.dat"));
        //不断地读取文件，直到文件末尾
        try {
            while (true){
                Object obj = ois.readObject();
                System.out.println(obj);
            }
        }catch (EOFException  e){
            System.out.println("文件读取结束");
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        writeToFile();
        readFromFile();
    }
}
